package com.njlime.core.sdk.wechat.customerService;

import com.alibaba.fastjson.JSONObject;
import com.njlime.core.sdk.wechat.WeChatUtil;
import com.njlime.core.sdk.wechat.jsapi.AccessToken;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.security.util.UserUtils;
import org.apache.log4j.Logger;

/**
 * 客服回消息
 * @author Herman.Xiong
 * @date 2016年1月13日15:09:29
 */
public class CustomerService {
	static Logger logger = Logger.getLogger(WeChatUtil.class);

	/**
	 * 给单个用户发消息
	 * @param unitId 单位id
	 * @param text 内容
	 * @return
	 */
	public static int send( String userOpenId,int unitId,String text) {
		try {
			// 获取单位公共号信息信息
			UnitWxConfig config = UserUtils.getUnitConfig(unitId);
			if (config != null) {
				AccessToken token = WeChatUtil.getAccessToken(config.getApp_id(), config.getApp_secret());
				System.out.println(token.getToken());
				if (token != null) {
					String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token.getToken();
					String data = "{\"touser\":\""+userOpenId+"\",\"msgtype\":\"text\",\"text\":{ \"content\":\""+ text +"\"}}";
					JSONObject json = WeChatUtil.httpRequest(requestUrl, "POST", data);
					System.out.println(data+"_____"+json.toJSONString());
					if (json.get("errcode") != null) {
						String errcode =   json.get("errcode").toString();
						return Integer.parseInt(errcode);
					}
				}
			}
		}catch (Exception e){
			logger.error(e);
		}
		return -1;
	}
	/**
	 * 给单个用户发消息
	 * @param unitId 单位id
	 * @param text 内容
	 * @param url 内容url
	 * @param picUrl 图片url
	 * @return
	 */
	public static int sendNews( String userOpenId,int unitId,String text,String description,String url,String picUrl) {
		try {
			// 获取单位公共号信息信息
			UnitWxConfig config = UserUtils.getUnitConfig(unitId);
			if (config != null) {
				AccessToken token = WeChatUtil.getAccessToken(config.getApp_id(), config.getApp_secret());
				System.out.println(token.getToken());
				if (token != null) {
					String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token.getToken();
					String data = "{\"touser\":\""+userOpenId+"\",\"msgtype\":\"news\",\"news\":{ "+
					"\"articles\": [{\"title\":\""+text+"\",\"description\":\""+description+"\",\"url\":\""+url+"\",\"picurl\":\""+picUrl+"\"}]"+"}}";
					JSONObject json = WeChatUtil.httpRequest(requestUrl, "POST", data);
					System.out.println(data+"_____"+json.toJSONString());
					if (json.get("errcode") != null) {
						String errcode =   json.get("errcode").toString();
						return Integer.parseInt(errcode);
					}
				}
			}
		}catch (Exception e){
			logger.error(e);
		}
		return -1;
	}
}
